import process from 'node:process'
import * as trpcExpress from '@trpc/server/adapters/express'
import express from 'express'
import ws from 'ws'
import { applyWSSHandler } from '@trpc/server/adapters/ws'
import cors from 'cors'
import { env } from '../../../env'
import { createAuthContext } from './context/authContext'
import { router } from './trpc'
import { codeGenRouter } from './router/codeGen.router'
import { logger } from './logger'

// root router to call
const appRouter = router({
  codeGen: codeGenRouter,
})

const wss = new ws.Server({
  port: env.V1_WS_PORT,
})
const handler = applyWSSHandler({ wss, router: appRouter, createContext: createAuthContext })

wss.on('connection', (ws) => {
  logger.info(`➕➕ Connection (${wss.clients.size})`)
  ws.once('close', () => {
    logger.info(`➖➖ Connection (${wss.clients.size})`)
  })
})
logger.info('✅ WebSocket Server listening on ws://localhost:3001')
process.on('SIGTERM', () => {
  logger.info('SIGTERM')
  handler.broadcastReconnectNotification()
  wss.close()
})

export type AppRouter = typeof appRouter

async function main() {
  // express implementation
  const app = express()
  app.use(cors())
  app.use((req, _res, next) => {
    // request logger
    logger.info('⬅️ ', req.method, req.path, req.body ?? req.query)

    next()
  })

  app.use(
    '/trpc',
    trpcExpress.createExpressMiddleware({
      router: appRouter,
      createContext: createAuthContext,
    }),
  )
  app.get('/', (_req, res) => res.send('hello'))
  app.listen(env.V1_HTTP_PORT, () => {
    logger.info(`listening on port ${env.V1_HTTP_PORT}`)
  })
}

void main()
